package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.example.library_common.adapter.JssBaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.LazyFragment
import com.example.library_common.db.ShopCarBean
import com.example.library_common.db.UserDatabase
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.PixUtils
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.GoodsDetailBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.GoodsDetailLikeListBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods.widget.GoodsFolderLayout
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods.widget.GoodsFolderLayoutToggleListener
import com.example.shushiyunsst.util.*

import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.example.wallet.utils.selectorIcon
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback

/**
 * 商品详情
 * */
@Route(path = GOODS_TEMP_DETAIL)
class GoodsDetailFragment : LazyFragment(), View.OnClickListener, GoodsFolderLayoutToggleListener {

    companion object {
        fun newInstance(): GoodsDetailFragment {
            val args = Bundle()
            val fragment = GoodsDetailFragment()
            fragment.arguments = args
            return fragment
        }
    }


    @JvmField
    @Autowired(name = GOODS_ID)
    var categoryId: String = ""

    override fun getLayoutId() = R.layout.goods_detail_fragment


    private lateinit var mGoodsPics: RecyclerView

    private var mGoodsPicsAdapter: JssBaseQuickAdapter<String>? = null

    private val pageSnap = LinearSnapHelper()

    private lateinit var mIntroduceGoods: XGridLayout

    private var mIntroduceGoodsAdapter: CommAdapter<String>? = null

    private lateinit var mGuessLike: XGridLayout

    private var mGuessLikeAdapter: CommAdapter<GoodsDetailLikeListBean>? = null

    private lateinit var headerBg: View

    private lateinit var mScrollView: ScrollView

    private val maxDistance = PixUtils.dp2px(240) * 1f

    private lateinit var mCollectionsTv: TextView

    private lateinit var mGoodSelect: ImageView

    private lateinit var goodsComment: ImageView

    private lateinit var selectedLabTv: TextView

    private lateinit var bottomLayout: View

    private var infoDao = GoodsDetailBean()

    private var mShopCar: ShopCarBean = ShopCarBean()

    private val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

    private lateinit var mGoodsFolderLayout: GoodsFolderLayout

    private val mGoodSelectPop = GoodSelectPop.newInstance()

    private val icon = AppGlobals.getApplication().getString(R.string.wallet_sst)

//    private var cml= selectorIcon()

//    private var cml= AppGlobals.getApplication().getString(R.string.wallet_fu_li_scored)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val cache = UserDatabase.getInstance()
            .shopCarBean()
            .getCache(user?.uid)
        if (cache != null) {
            mShopCar = cache
        } else {
            mShopCar.userId = user?.uid
        }

    }

    override fun lazyInit() {

        val maps = mapOf(
            "goodsId" to categoryId,
            "uid" to user?.uid,
        )

        RestClient.builder()
            .url(R.string.queryGoodsById)
            .raw(JSON.toJSONString(maps))
            .success {
                mScrollView.scrollTo(0,0)
                infoDao = JSON.parseObject(it, infoDao.javaClass)

                val cache = UserDatabase.getInstance()
                    .shopCarBean()
                    .getCache(user?.uid)

                val shopCarList22 = cache?.shopCarList22 ?: emptyList()

                for (e in shopCarList22) {
                    if (infoDao.goods == e) {
                        infoDao.goods = e
                        break
                    }
                }

                fillGoodsPics()

                fillIntroduceGoods()

                fillGuessLikeAdapter()

            }.failure {

            }.error { _, _ ->

            }
            .build()
            .post()

    }

    private fun fillGuessLikeAdapter() {

        mGuessLikeAdapter?.clear()

        mGuessLikeAdapter?.addAll(infoDao.likeList)
    }

    private fun fillIntroduceGoods() {

        val goodsPics = JSON.parseObject(infoDao.goods.goodsContent)

        val pics = goodsPics["pics"] ?: return

        val array = JSON.parseArray(pics.toString())

        val ls = mutableListOf<String>()

        for (e in array.iterator()) {

            if (e is JSONObject) {

                val url = e["url"].toString()

                ls.add(url)
            }
        }
        mIntroduceGoodsAdapter?.clear()
        mIntroduceGoodsAdapter?.addAll(ls)
        mIntroduceGoods.maxItem = ls.size
    }

    @SuppressLint("SetTextI18n")
    private fun fillGoodsPics() {


        selectedLabTv = rootView.findViewById(R.id.selectedLabTv)
        selectedLabTv.text = infoDao.goods.selectedLabStr

        mCollectionsTv.isSelected = infoDao.goods.isCollected

        val moneyTv: TextView = rootView.findViewById(R.id.moneyTv)
        val givenCml="${infoDao.goods?.givenCml}"
        moneyTv.text ="${infoDao.goods.goodsPrice} $icon"+
        _mActivity.getString(R.string.wallet_fu_li_scored)

//        moneyTv.text = "${infoDao.goods.goodsPrice} $icon  赠送 ${infoDao.goods.givenCml} $cml"

        val goodsTitleLine: TextView = rootView.findViewById(R.id.goodsTitleLine)
        goodsTitleLine.text = infoDao.goods.goodsName

        val goodsOldPrice: TextView = rootView.findViewById(R.id.goodsOldPrice)
        goodsOldPrice.text = "原价:${infoDao.goods.goodsOldPrice} $icon"

        val goodsStock: TextView = rootView.findViewById(R.id.goodsStock)
        goodsStock.text = "库存：${infoDao.goods.goodsStock} 件"

        val goodsSales: TextView = rootView.findViewById(R.id.goodsSales)
        goodsSales.text = "销量：${infoDao.goods.goodsSales} 件"

        mGoodsPics.layoutManager =
            LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false)
        mGoodsPicsAdapter = object : JssBaseQuickAdapter<String>(R.layout.goods_detail_pics) {

            override fun convert(holder: JssBaseViewHolder?, item: String?) {
                super.convert(holder, item)
                holder?.setImageNetUrl(R.id.icon, item)
            }
        }
        mGoodsPics.adapter = mGoodsPicsAdapter
        pageSnap.attachToRecyclerView(mGoodsPics)

        val goodsPics = JSON.parseObject(infoDao.goods.goodsPics)

        val pics = goodsPics["pics"] ?: return

        val array = JSON.parseArray(pics.toString())

        val ls = mutableListOf<String>()

        for (e in array.iterator()) {

            if (e is JSONObject) {

                val url = e["url"].toString()

                ls.add(url)
            }
        }
        mGoodsPicsAdapter?.clears()
        mGoodsPicsAdapter?.addData(ls)
    }

    override fun initView(view: View) {

        mGoodsFolderLayout = view.findViewById(R.id.mGoodsFolderLayout)

        mGoodsFolderLayout.setToggleListener(this)

        view.findViewById<View>(R.id.addShoppingCar)
            .setOnClickListener(this)

        view.findViewById<View>(R.id.payingNow)
            .setOnClickListener(this)

        view.findViewById<View>(R.id.carShop)
            .setOnClickListener(this)

        bottomLayout = view.findViewById(R.id.bottomLayout)
        view.findViewById<View>(R.id.mPageBack)
            .setOnClickListener(this)

        mCollectionsTv = view.findViewById(R.id.mCollectionsTv)
        mCollectionsTv.setOnClickListener(this)


        mGoodSelect = view.findViewById(R.id.mGoodSelect)
        mGoodSelect.setOnClickListener(this)

        goodsComment = view.findViewById(R.id.goodsComment)
        goodsComment.setOnClickListener(this)


        mGoodsPics = view.findViewById(R.id.mGoodsPics)
        mIntroduceGoods = view.findViewById(R.id.mIntroduceGoods)
        mGuessLike = view.findViewById(R.id.mGuessLike)

        headerBg = view.findViewById(R.id.headerBg)
        mScrollView = view.findViewById(R.id.mScrollView)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            mScrollView.setOnScrollChangeListener { _, _, scrollY, _, _ ->

                val alpha = scrollY * 1f / maxDistance

                headerBg.alpha = if (alpha > 1f) 1f else alpha
            }
        }

        loadRootFragment(R.id.albumFolderPopupMenuViews, mGoodSelectPop)

        mGuessLikeAdapter =
            object : CommAdapter<GoodsDetailLikeListBean>(
                _mActivity, R.layout.goods_detail_guess_like
            ) {
                override fun convert(
                    holder: XQuickViewHolder?, item: GoodsDetailLikeListBean?, position: Int
                ) {
                    val givenCml="${infoDao.goods?.givenCml}"
                    holder?.setText(R.id.mGoodsPrice,
                        _mActivity.getString(R.string.wallet_fu_li_scored)
                    )
//                        ?.setText(R.id.payedCount, "赠送${item?.givenCml} $cml")
                        ?.setText(R.id.mGoodsPrice, "\$${item?.goodsPrice}")
                        ?.setText(R.id.goodsName, item?.goodsName)

                        ?.displayImage(R.id.mGoodsPics, item?.parseGoodsPics(), R.mipmap.trees_er)
                        ?.setOnClickListener {
                            categoryId=item?.gid.toString()
                            lazyInit()
                        }
                }

            }
        mGuessLike.setAdapter(mGuessLikeAdapter, lifecycle)

        mIntroduceGoodsAdapter =
            object : CommAdapter<String>(_mActivity, R.layout.goods_detail_introduce_goods) {
                override fun convert(holder: XQuickViewHolder?, item: String?, position: Int) {
                    holder?.displayImage(R.id.icon, item)
                }

            }
        mIntroduceGoods.setAdapter(mIntroduceGoodsAdapter, lifecycle)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.addShoppingCar -> {
                val text = infoDao.goods.selectedLabStr

                if (!TextUtils.isEmpty(text)) {
                    saveGoods()
                    return
                }
                mGoodSelectPop.setInfoDao(infoDao)
                mGoodsFolderLayout.toggle()

            }

            R.id.payingNow -> {
                start(ConfirmSingleTakeOrderFragment.newInstance(infoDao))
            }

            R.id.carShop -> {
                ARouter.getInstance()
                    .build(SHOP_CAR)
                    .startNavigation(this)
            }
            R.id.mPageBack -> {
                onBackPressedSupport()
            }
            R.id.mCollectionsTv -> {

                val maps = mapOf(
                    "goodsId" to infoDao.goods.gid,
                    "uid" to user?.uid,
                    "opt" to infoDao.goods.toggleCollecting(),
                )
                mCollectionsTv.isSelected = infoDao.goods.isCollected
                RestClient.builder()
                    .url(R.string.saveOrCancelCollect)
                    .raw(JSON.toJSONString(maps))
                    .success {

                    }.failure {

                    }.error { _, _ ->

                    }
                    .build()
                    .post()


            }

            R.id.mGoodSelect -> {
                mGoodSelectPop.setInfoDao(infoDao)

                mGoodsFolderLayout.toggle()
            }
            R.id.goodsComment -> {

                ARouter.getInstance()
                    .build(GOODS_COMMENT)
                    .withString(GOODS_ID, infoDao.goods?.gid.toString())
                    .startNavigation(this)
            }
        }
    }

    private fun saveGoods() {

        val shopCarList = mShopCar.shopCarList22

        var flag = false

        var goods = infoDao.goods

        for (e in shopCarList) {

            if (e == goods) {

                flag = true

                goods = e
                break
            }
        }
//
        if (!flag) {
            shopCarList.add(goods)
        } else {
            goods.selectedCount += 1
        }
        mShopCar.shopCarList = JSON.toJSONString(shopCarList)

        UserDatabase.getInstance()
            .shopCarBean()
            .save(mShopCar)

        Toast.makeText(_mActivity, "加入购物车成功", Toast.LENGTH_SHORT).show()
    }

    override fun onToggle() {
        if (!mGoodsFolderLayout.isOnShowIng()) {
            selectedLabTv.text = infoDao.goods.selectedLabStr
        }
    }
}